<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2019/09/04
 * Time: 14:58
 */

namespace business\elasticsearch\repositories;

use business\elasticsearch\models\SupplierBasicModel;
use business\elasticsearch\types\SupplierBasicConfigType;
use business\elasticsearch\repositories\EsQuery;
use yii\elasticsearch\Query;

class SupplierBasicRepository
{
    /**
     * 创建供应商数据索引
     * @return mixed
     */
    public function createSupplierBasicIndex()
    {
        return SupplierBasicModel::getDb()
            ->createCommand()
            ->createIndex(
                SupplierBasicModel::index(),
                [
                    'settings' => [
                        'index' => [
                            'number_of_shards' => 5,
                            'number_of_replicas' => 1,
                            'analysis.analyzer.default.type' => 'ik_max_word',
                        ]
                    ],
                    'mappings' => [
                        SupplierBasicModel::type() => SupplierBasicConfigType::mapConfig()
                    ]
                ]
            );
    }

    /**
     * 查询供应商单条记录
     * @param array $condition
     * @return array|bool
     */
    public function querySupplierBasicOne($condition = [])
    {
        return (new Query())
            ->from(SupplierBasicModel::index(), SupplierBasicModel::type())
            ->where($condition)
            ->one();
    }

    /**
     * 保存供应商数据记录
     * @param array $data
     * @param int $id
     * @return array
     */
    public function saveSupplierBasicRecord($data = [], $id = 0)
    {
        if (!empty($data)) {
            return SupplierBasicModel::getDb()
                ->createCommand()
                ->insert(SupplierBasicModel::index(), SupplierBasicModel::type(), $data, $id);
        }

        return [];
    }

    /**
     * 查询供应商数据列表
     * @param $condition
     * @param array $include
     * @param array $aggregations
     * @param int $from
     * @param int $size
     * @param array $orderBy
     * @return array
     */
    public function querySupplierBasicList
    (
        $condition,
        $include = [],
        $aggregations = [],
        $from = 0,
        $size = 0,
        $orderBy = []
    ) {
        $query = (new EsQuery())
            ->source($include)
            ->from(SupplierBasicModel::index(), SupplierBasicModel::type())
            ->query($condition);

        if (!empty($aggregations)) {
            foreach ($aggregations as $aggregation) {
                $query->addAggs($aggregation['name'], $aggregation['options']);
            }
        }

        $query->orderBy($orderBy)->offset($from)->limit($size);

        return [
            $query->count(),
            !empty($aggregations) ? $query->createCommand()->search()['aggregations'] : $query->all()
        ];
    }
}
